<template>
  <view class="ai-chat-page">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="history-icon" @click="showHistory = true">
        <!-- 这里可以替换成实际的小标图片 -->
        <text>≡</text>
      </view>
      <text class="nav-title">{{ displayTitle }}</text>
      <!-- 添加加号图标 -->
      <view class="add-icon" @click="startNewConversation">
        <text>+</text>
      </view>
    </view>

    <!-- 搜索历史对话框 -->
    <view v-if="showHistory" class="history-dialog">
      <view class="dialog-header">
        <text>搜索历史</text>
        <text @click="showHistory = false">×</text>
      </view>
      <view class="history-list" v-for="(item, index) in searchHistory" :key="item.uid" @tap="getAiHistoryMessage(item.uid)">
        <!-- 显示消息序号 -->
        <!-- 显示历史消息信息：第一个：时间，第二个：上一条提问  searchHistory要改成aiHistory类型的-->
        <view>
          <view class="uTime">{{ item.uTime }}</view>
          <view class="lastQuestion">{{
            item.lastQuestion.length>20?item.lastQuestion.slice(0,20)+'……':item.lastQuestion}}</view>
        </view>
      </view>
    </view>

    <!-- 聊天内容区域 -->
    <view class="chat-content">
      <view v-for="(message, index) in chatMessages" :key="index"
        :class="['message-item', message.isAi ? 'ai-message' : 'user-message']">
        <template v-if="message.isAi">
          <view class="avatar">
            <image src="/static/ai-avatar.png" mode="aspectFit" />
          </view>
          <view class="message-content">{{ message.content }}</view>
        </template>
        <template v-else>
          <view class="message-content">{{ message.content }}</view>
          <view class="avatar">
            <image src="/static/user-avatar.png" mode="aspectFit" />
          </view>
        </template>
      </view>
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <input type="text" ref="inputRef" v-model="inputMessage" placeholder="请输入聊天内容" @input="updateTitle"
        @confirm="sendMessage" />
      <button @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import type { aiHistroy, aiHistoryPageInfo,aiMessage,uid } from '@/types/ai';
import { addAiHistoryAPI, getHistoryAPI, getHistoryPageInfoAPI, sendAiMessageAPI, getAiMessageListAPI, sendMessageAPI } from '@/service/ai-chat';
import { useMemberStore } from '@/stores';
import { onLoad } from '@dcloudio/uni-app';

// // uniapp 获取页面参数
// const query = defineProps<{
//   type: string|number
// }>()
// // console.log(query)
// const currUrlMap = urlMap.find((v) => v.type === query.type)
const memberStore = useMemberStore();
// 对话id（对话的唯一标识）
const uid = new Date().getTime() + '-' + memberStore.profile!.id;

// memberStore.profile?.id
// 初始标题
const displayTitle = ref('AI对话');
// 输入内容
const inputMessage = ref('');
// 是否显示搜索历史对话框
const showHistory = ref(false);
// 搜索历史
const searchHistory = ref<aiHistroy[]>([{uTime:'2024-05-27 19:30:55',lastQuestion:'你好',uid:"1",userId:1}]);
// 聊天消息列表
const chatMessages = ref<aiMessage[]>([]);

// 定义输入框的 ref
const inputRef = ref<HTMLInputElement | null>(null);
const aiHistoryPagedata = ref<aiHistoryPageInfo>({
  userId: memberStore.profile?.id as number,
  pageNum: 1,
  pageSize: 10,
});
// 获取历史记录分页信息
const getHistoryPageInfoData = async () => {
  try {
    const userId = aiHistoryPagedata.value.userId;
    const pageNum = aiHistoryPagedata.value.pageNum;
    const pageSize = aiHistoryPagedata.value.pageSize;
    const res = await getHistoryPageInfoAPI(userId, pageNum, pageSize);
    console.log(res);
    // 假设 API 返回的数据结构为 { data: aiHistroy[] }
    if (res.data && Array.isArray(res.data)) {
      // 转换数据格式以匹配 searchHistory 的类型
      const transformedData = res.data.map(item => ({
        // id: uuidv4(),
        content: item.lastQuestion, // 假设 lastQuestion 是搜索内容
        time: item.uTime // 假设 uTime 是搜索时间
      }));
      // 更新搜索历史
      // searchHistory.value = transformedData;
    }
  } catch (error) {
    console.error('获取历史记录分页信息失败:', error);
    // 可以在这里添加错误提示，例如使用 uni.showToast
    uni.showToast({
      title: '获取历史记录失败',
      icon: 'none',
      duration: 2000
    });
  }
};
onLoad(() => {
  //从这开始
  getHistoryPageInfoData();
})

// 更新标题
const updateTitle = () => {
  if (inputMessage.value) {
    displayTitle.value = inputMessage.value.slice(0, 12) + (inputMessage.value.length > 12 ? '...' : '');
  } else {
    displayTitle.value = 'AI对话';
  }
};

// 发送消息
const sendMessage = async () => {
  console.log('发送消息:', inputMessage.value);
  if (inputMessage.value != '') {
    let data2: aiMessage = {
      uid: uid,
      userId:memberStore.profile?.id as number,
      isAi: false,
      content: inputMessage.value,
      sendTime: new Date()
    }
    // 添加用户消息到聊天列表
    chatMessages.value.push(data2);
    // 添加搜索历史
    // searchHistory.value.push(inputMessage.value);
    // 清空输入框
    inputMessage.value = '';
    // 恢复标题
    displayTitle.value = 'AI对话';

  
   //发送消息到后端服务
   const res= await sendMessageAPI(data2)
   chatMessages.value.push(res.data)
  }  
   
};

const getAiHistoryMessage = async(uid:string) => {
  //请求，把uid传入  
    const res = await getAiMessageListAPI(uid)
    console.log(res) 
  //res是响应回来的信息，aiMessage.vale = res.data
    chatMessages.value = res.data;

}

// 开启新对话
const startNewConversation = () => {
  if (chatMessages.value.length > 0) {
    // 截取用户最后一条发送的消息
    const lastUserMessage = chatMessages.value.filter(msg => !msg.isAi).pop();
    let d: Date = new Date()
    //将时间戳类型的信息转化为yyyy-MM-dd hh:mm:ss的格式
    let dateString = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-') + ' ' + [d.getHours(), d.getMinutes(), d.getSeconds()].join(':')
    if (lastUserMessage) {
      // 添加搜索历史
      searchHistory.value.unshift({
        // id: uuidv4(),
        userId: memberStore.profile?.id as number,
        uid: uid,
        lastQuestion: lastUserMessage.content,
        uTime: dateString
      });
    }
    //2.使用扩展运算符拼接新的历史记录到搜索历史数组前面
    // let a = 1;
    // let b = [2,3,4]
    // //吧b变成a + b（即[1,2,3,4]）
    // const c = [a,...b]
    // b = c;
    // if (lastUserMessage) {
    //   const newHistoryItem = {
    //     userId: memberStore.profile?.id as number,
    //     uid: uid,
    //     lastQuestion: lastUserMessage.content,
    //     uTime: dateString
    //   };
    //   // 使用扩展运算符拼接新的历史记录到搜索历史数组前面
    //   searchHistory.value = [newHistoryItem, ...searchHistory.value];

    // 清空聊天消息列表
    chatMessages.value = [];
    // 清空输入框
    inputMessage.value = '';
    // 恢复标题
    displayTitle.value = 'AI对话';
    // 显示轻提示
    uni.showToast({
      title: '已开启新对话',
      icon: 'success',
      duration: 2000
    });
   addAiHistoryAPI({userId: memberStore.profile?.id as number,uid: uid,lastQuestion: lastUserMessage?.content as string,uTime: dateString})
  } 
};

// 按键事件处理函数
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    sendMessage();
  }
};

onMounted(() => {
  if (inputRef.value) {
    inputRef.value.addEventListener('keydown', handleKeyDown);
  }
});

onUnmounted(() => {
  if (inputRef.value) {
    inputRef.value.removeEventListener('keydown', handleKeyDown);
  }
});
</script>

<style scoped lang="scss">
.ai-chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  background: #fff;
  border-bottom: 1rpx solid #e6eaf0;
  justify-content: space-between;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
}

.history-icon, .add-icon {
  font-size: 44rpx;
  color: #0b8cef;
  cursor: pointer;
  user-select: none;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222;
  flex: 1;
  text-align: center;
}

.history-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 60vw;
  max-width: 420px;
  height: 100vh;
  background: #fff;
  box-shadow: 4rpx 0 24rpx rgba(11,140,239,0.08);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  border-radius: 0 16rpx 16rpx 0;
  border-right: 1rpx solid #e6eaf0;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 24rpx 16rpx 24rpx;
  border-bottom: 1rpx solid #e6eaf0;
  font-size: 30rpx;
  color: #0b8cef;
  font-weight: 600;
}

.dialog-header text:last-child {
  font-size: 36rpx;
  color: #bbb;
  cursor: pointer;
}

.history-list {
  flex: 1;
  padding: 0 24rpx;
  overflow-y: auto;
}

.history-list > view {
  width: 100%;
  background: #f7faff;
  display: flex;
  flex-direction: column;
  margin-bottom: 18rpx;
  padding: 18rpx 20rpx;
  border-radius: 10rpx;
  border: 1rpx solid #e6eaf0;
  box-shadow: 0 2rpx 8rpx rgba(11,140,239,0.03);
  transition: background 0.2s;
}
.history-list > view:active {
  background: #eaf4fe;
}
.uTime {
  font-size: 22rpx;
  color: #a0a0a0;
  margin-bottom: 6rpx;
}
.lastQuestion {
  font-size: 28rpx;
  color: #222;
  font-weight: 500;
  line-height: 1.4;
}

.chat-content {
  flex: 1;
  background: #fff;
  overflow-y: auto;
  padding: 32rpx 0 32rpx 0;
  display: flex;
  flex-direction: column;
  gap: 18rpx;
}

.message-item {
  display: flex;
  align-items: flex-end;
  padding: 0 32rpx;
}

// AI消息：头像在左，气泡在右
.ai-message {
  flex-direction: row;
  justify-content: flex-start;
}
.ai-message .avatar {
  order: 0;
  margin-right: 16rpx;
  margin-left: 0;
}
.ai-message .message-content {
  order: 1;
  background: #f2f8fd;
  color: #0b8cef;
  border-radius: 16rpx 16rpx 16rpx 0;
  margin-left: 0;
  margin-right: auto;
  box-shadow: 0 2rpx 8rpx rgba(11,140,239,0.06);
}

// 用户消息：头像在右，气泡在左
.user-message {
  flex-direction: row-reverse;
  justify-content: flex-end;
}
.user-message .avatar {
  order: 0;
  margin-left: 16rpx;
  margin-right: 0;
}
.user-message .message-content {
  order: 1;
  background: #0b8cef;
  color: #fff;
  border-radius: 16rpx 16rpx 0 16rpx;
  margin-right: 0;
  margin-left: auto;
  box-shadow: 0 2rpx 8rpx rgba(11,140,239,0.10);
}

.avatar {
  width: 72rpx;
  height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #eaf4fe;
  border-radius: 50%;
  overflow: hidden;
}
.avatar image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-content {
  max-width: 70vw;
  padding: 20rpx 28rpx;
  font-size: 28rpx;
  line-height: 1.7;
  word-break: break-all;
  box-sizing: border-box;
  min-height: 48rpx;
  display: flex;
  align-items: center;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 18rpx 24rpx 24rpx 24rpx;
  background: #fff;
  border-top: 1rpx solid #e6eaf0;
  box-shadow: 0 -2rpx 8rpx rgba(11,140,239,0.03);
  gap: 16rpx;
}

input {
  flex: 1;
  font-size: 28rpx;
  border: 1rpx solid #e6eaf0;
  padding: 16rpx 24rpx;
  border-radius: 24rpx;
  background: #f7faff;
  outline: none;
  color: #222;
  transition: border 0.2s;
}
input:focus {
  border: 1rpx solid #0b8cef;
  background: #fff;
}

button {
  font-size: 28rpx;
  min-width: 120rpx;
  height: 72rpx;
  background: #0b8cef;
  color: #fff;
  border: none;
  border-radius: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(11,140,239,0.08);
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
button:active {
  background: #086bb5;
}
</style>